package com.shen.library_nettysocket.handler


import com.shen.library_nettysocket.netty.NettyTcpClient
import com.shen.library_nettysocket.protobuf.MessageProtobuf
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.handler.timeout.IdleState
import io.netty.handler.timeout.IdleStateEvent
import java.lang.Exception

/**
 * 「心跳任务」管理器
 */
class HeartbeatHandler(private val imsClient: NettyTcpClient) : ChannelInboundHandlerAdapter() {

    private var heartbeatTask: HeartbeatTask? = null
    private fun getHeartbeatTask(ctx: ChannelHandlerContext): HeartbeatTask?{
        if (heartbeatTask == null) {
            heartbeatTask = HeartbeatTask(ctx)
        }
        return heartbeatTask
    }

    @Throws(Exception::class)
    override fun userEventTriggered(ctx: ChannelHandlerContext, evt: Any) {
        super.userEventTriggered(ctx, evt)

        if (evt is IdleStateEvent) {
            when (evt.state()) {
                // 「规定时间内」没收到「服务端心跳包」响应，进行「重连操作」
                IdleState.READER_IDLE -> imsClient.resetConnect(false)
                // 「规定时间内」没向「服务端·发送心跳包」，即「发送一个心跳包」
                IdleState.WRITER_IDLE -> imsClient.loopGroup?.execWorkTask(getHeartbeatTask(ctx))
            }
        }
    }


    private inner class HeartbeatTask(private val ctx: ChannelHandlerContext) : Runnable {
        override fun run() {
            if (ctx.channel().isActive) {
                val heartbeatMsg: MessageProtobuf.Msg = imsClient.heartbeatMsg ?: return
                println("发送心跳消息，message=${heartbeatMsg}当前心跳间隔为：${imsClient.heartbeatInterval}ms")
                imsClient.sendMsg(heartbeatMsg, false)
            }
        }
    }

}